<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use EasyWeChat\Factory;
use think\facade\Session;
use think\facade\View;
use app\model\JdHistory;
use app\model\JdUser;
use app\model\JdBeanRecord;
use think\facade\Db;

class Index extends BaseController
{
    protected $app;

    public function __construct()
    {
        $config = config('wechat');
        $this->app = Factory::officialAccount($config);
    }

    protected function getWechatCallbackUrl() {
      return Request::domain() . "/wechat/oauth_callback?return_url=" . urlencode(Request::url());
    }

    public function index() {
        $openid = Session::get('openid');
        if(!$openid) {
            $oauth = $this->app->oauth;
            
            Session::set('wx_oauth_return_url', Request::url());
            $oauth->redirect($this->getWechatCallbackUrl())->send();
            return;
        }
        return Request::domain();
    }

    public function openid()
    {
        $openid = Session::get('openid');
        if(!$openid) {
            $oauth = $this->app->oauth;
            
            Session::set('wx_oauth_return_url', Request::url());
            $oauth->redirect($this->getWechatCallbackUrl())->send();
            return;
        }
        return $openid;
    }

    public function delopenid()
    {
        $openid = Session::delete('openid');
    }


    public function data($id)
    {
        $openid = Session::get('openid');
        if(!$openid) {
            $oauth = $this->app->oauth;
            
            Session::set('wx_oauth_return_url', Request::url());
            $oauth->redirect($this->getWechatCallbackUrl())->send();
            return;
        }
        $yesterday = date("Y-m-d",strtotime("-1 day"));

        $user = JdUser::find($id);
        $yesterdayData = JdHistory::where('uid', $user->id)->where('date', $yesterday)->find();
        return View::fetch('data', [
            'user'  => $user,
            'yesterday' => $yesterdayData
        ]);
    }

    public function my()
    {
        $openid = Session::get('openid');
        if(!$openid) {
            $oauth = $this->app->oauth;
            
            Session::set('wx_oauth_return_url', Request::url());
            $oauth->redirect($this->getWechatCallbackUrl())->send();
            return;
        }
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $users = JdUser::where('openid', $openid)->select();
        foreach ($users as $key => $user) {
            # code...
            $yesterdayData = JdHistory::where('uid', $user->id)-> where('date', $yesterday)->find();
            $user->yesterday = $yesterdayData;
        }
        return View::fetch('my', [
            'users'  => $users
        ]);
    }

    public function chart($id){
        $user = JdUser::find($id);
        $start = date("Y-m-d",strtotime("-30 day"));

        // 最近30天收入支付情况
        $historys = JdHistory::where('uid', $id)-> where('date', '>', $start)->select();
        $date = [];
        $increases = [];
        $decreases = [];
        $totals = [];
        foreach ($historys as $key => $value) {
            $date[] = date("d号",strtotime($value->date));
            $increases[] = $value->increase;
            $decreases[] = $value->decrease;
            $totals[] = $value->total;
        }
        // 最近30天总收入
        $incomeAll = Db::table('jd_bean_record')
        ->where('uid', $id)
        ->where('amount', '>', 0)
        ->where('datetime', '>=', $start)
        ->sum('amount');
        // 最近30天总支出
        $expenseAll = Db::table('jd_bean_record')
        ->where('uid', $id)
        ->where('amount', '<', 0)
        ->where('datetime', '>=', $start)
        ->sum('amount');
        // 收入类型统计
        $incomeStatictis = Db::table('jd_bean_record')
        ->where('uid', $id)
        ->where('amount', '>', 0)
        ->where('datetime', '>=', $start)
        ->field('event_message,SUM(amount) AS sum_amount')
        ->group('event_message')
        ->order('sum_amount', 'desc')
        ->select();
        $incomeLegend = [];
        $incomeData = [];
        foreach ($incomeStatictis as $key => $value) {
            $incomeLegend[] = $value['event_message'];
            $obj = new \StdClass();
            $obj->name = $value['event_message'];
            $obj->value = $value['sum_amount'];
            $incomeData[] = $obj;
        }
        // 支出类型统计
        $expenseStatictis = Db::table('jd_bean_record')
        ->where('uid', $id)
        ->where('amount', '<', 0)
        ->where('datetime', '>=', $start)
        ->field('event_message,SUM(amount) AS sum_amount')
        ->group('event_message')
        ->order('sum_amount', 'desc')
        ->select();
        $expenseLegend = [];
        $expenseData = [];
        foreach ($expenseStatictis as $key => $value) {
            $expenseLegend[] = $value['event_message'];
            $obj = new \StdClass();
            $obj->name = $value['event_message'];
            $obj->value = $value['sum_amount'];
            $expenseData[] = $obj;
        }
        return View::fetch('chart', [
            'user' => $user,
            'date'  => json_encode($date),
            'increases'  => json_encode($increases),
            'decreases'  => json_encode($decreases),
            'totals'  => json_encode($totals),
            'incomeLegend'  => json_encode($incomeLegend, JSON_UNESCAPED_UNICODE),
            'incomeData'  => json_encode($incomeData, JSON_UNESCAPED_UNICODE),
            'expenseLegend'  => json_encode($expenseLegend, JSON_UNESCAPED_UNICODE),
            'expenseData'  => json_encode($expenseData, JSON_UNESCAPED_UNICODE),
            'incomeAll'  => $incomeAll,
            'expenseAll'  => $expenseAll,
        ]);
    }
}
